﻿@model ArivisTests.Models.TestRun
@using ArivisTests.Models;

@{
    ViewBag.Title = "Edit";

    List<UserProfile> users;
    List<TestScenario> scenarios;
    using (var db = new ArivisTestsDBContext())
    {
        users = db.ActiveTester.ToList();
        scenarios = db.TestScenarios.ToList();
    }
}

@section Navigation{
    @Html.ActionLink("Test Runs", "Index", "TestRun") &rsaquo;
    @Html.ActionLink(Model.Name, "Details", "TestRun", new { id = Model.Id}, null) &rsaquo;
    Assign Tester
}

<table style="margin-top:1em; margin-bottom:1em;">
    <tr>
        <td style="padding:0;vertical-align:middle;"><input type="checkbox" onchange="toggleFinishedTests();" id="toggleFinished"/></td>
        <td style="padding:0;vertical-align:middle;"><label for="toggleFinished">Hide finished tests</label></td>
    </tr>
</table>

@using (Html.BeginForm()) {
    @Html.HiddenFor(model => model.Id)
    @showTests(Model, null)
    foreach (var user in users.OrderBy(x => x))
    {
        @showTests(Model, user)
    }
    <input type="submit" value="Save" />
}

@if (scenarios.Count > 0)
{
    var listItems = scenarios.Select(s => new SelectListItem() { Value = s.Id.ToString(), Text = s.Name });
    var userListItems = users.Select(u => new SelectListItem() { Value = u.UserId.ToString(), Text = u.UserName });
    using (Html.BeginForm("AddScenario", "AssignTest")) {
        @Html.HiddenFor(model => model.Id)
        <table>
            <tr>
                <td>Scenario:&nbsp;@Html.DropDownList("scenario", listItems)</td>
                <td>User:&nbsp;@Html.DropDownList("user", userListItems, "")</td>
                <td><input type="submit" value="Add Test"/></td>
            </tr>
        </table>
    }        
}

<p>
@Html.ActionLink("View", "Details", "TestRun", new { id=Model.Id }, null) |
@Html.ActionLink("Edit", "Edit", "TestRun", new { id=Model.Id }, null) |
@Html.ActionLink("Delete", "Delete", "TestRun", new { id=Model.Id }, null) |
@Html.ActionLink("Assign Tester Automatic", "Automatic", "AssignTest", new { id = Model.Id }, null)
</p>

@helper showTests(TestRun run, UserProfile user)
{
    var userId = (user == null) ? 0 : user.UserId;
    IEnumerable<TestCase> userTests = run.Tests;
    userTests = (user == null) ? userTests.Where(test => test.User == null) : userTests.Where(test => test.User != null && test.User.UserId == user.UserId);
    userTests = userTests.OrderBy(test => test.Order);
    <h4 style="margin:0;">
        @MvcHtmlString.Create(user == null ? "[no tester]" : user.UserName) <span style="font-weight:normal;padding-left:1em;"></span>
    </h4>
    <div class="sortable">
    <input type="hidden" name="user_@userId" />
    @foreach (var test in userTests)
    {
        string className = test.Result == null ? "noresult" : "result";
        string testShortName = test.Name.Substring(0, test.Name.IndexOf(' '));
        int width = test.Scenario.Duration * 3;
        var sb = new System.Text.StringBuilder();
        sb.AppendFormat("<span ");
        sb.AppendFormat("style='width:{0}px;' ", test.Scenario.Duration * 3);
        sb.AppendFormat("id='testcase_{0}' ", test.Id);
        sb.AppendFormat("class='{0}' ", className);
        sb.AppendFormat("data-duration='{0}' ", test.Scenario.Duration);
        sb.AppendFormat("data-scenario='{0}' ", test.Scenario.Id);
        sb.AppendFormat("title='{0} ({1}min)' ", test.Name, test.Scenario.Duration);
        sb.Append(">");
        sb.Append(testShortName);
        sb.Append("</span>");
        @Html.Raw(sb.ToString())
    }
    </div>
}

@section Scripts {
    <style type="text/css">
        .sortable {
            margin-bottom:1em;
            min-height:23px;
            border: 1px solid lightgray;
        }
        .sortable * {
            display: inline-block;
            margin: 1px;
            vertical-align: middle;
            text-align: center;
            border: 1px solid rgba(0, 0, 0, 0.25);
        }

        .sortable .result {
            background-color: rgba(144, 238, 144, 0.30);
            /*background-image: url("/Images/accept.png");*/
            background-position: left center;
            background-repeat: no-repeat;
        }

        .sortable .noresult {
            cursor: pointer;
            background-color:  rgba(240, 128, 128, 0.30);
        }

            .sortable .noresult.duplicate {
                background-image: url("/Images/exclamation.png");
                background-position: left center;
                background-repeat: no-repeat;
            }

        .sortable .myplaceholder {
            background-color: rgba(240, 128, 128, 0.15);
        }
    </style>
    <script type="text/javascript">
        function toggleFinishedTests() {
            jQuery('.result').fadeToggle();
        }
        function handleSortableChanged() {
            jQuery('.sortable').each(function (index, element) {
                updateTest(jQuery(element));
            });
        }

        function contains(array, value) {
            for (var i = 0; i < array.length; i++) {
                if (array[i] == value) return true;
            }
            return false;
        }

        function serialize(array) {
            if (array.length == 0)
                return "";
            var result = array[0];
            for (var i = 1; i < array.length; i++) {
                result += ";" + array[i];
            }
            return result;
        }

        function updateTest(sortable) {
            var ids = new Array();
            var scenarios = new Array();
            var sumDuration = 0;
            // get finished tests
            var tests = sortable.find('.result');
            tests.each(function (index, element) {
                // get executed scenarios
                var scenario = Number(jQuery(element).attr('data-scenario'));
                scenarios.push(scenario);
            });
            // check unfinished tests
            tests = sortable.find('.noresult');
            tests.removeClass('duplicate');
            tests.each(function (index, element) {
                var jqElement = jQuery(element);
                // test-ids
                var id = element.id.substr(9);
                ids.push(id);
                // duration
                sumDuration += Number(jqElement.attr('data-duration'));
                // check for duplicate scenarios
                var scenario = Number(jqElement.attr('data-scenario'));
                if (contains(scenarios, scenario)) {
                    jqElement.addClass('duplicate');
                }
                scenarios.push(scenario);
            });

            // store test ids
            sortable.find('input').val(serialize(ids));

            // format text
            var text = "";
            var count = tests.get().length;
            var hours = Math.round(sumDuration / 60);
            var minutes = sumDuration % 60;
            if (count > 0) text = count + " tests, ";
            if (hours > 0) text += (hours + "h ")
            if (minutes > 0) text += (minutes + "min");

            // set text
            sortable.prev().children().text(text);
        }

        jQuery(document).ready(new function () {
            jQuery('.sortable').sortable({
                connectWith: '.sortable',
                items: '.noresult',
                placeholder: 'myplaceholder',
                forcePlaceholderSize: true,
                appendTo: document.body,
                update: handleSortableChanged,
            }).disableSelection();
            handleSortableChanged();
        });
    </script>
}